let departmentModule = (function () {
  let $tableBox = $('.tableBox'),
    $tbody = $tableBox.find("tbody");

  // 获取部门信息并渲染绑定
  async function bindHTML() {
    let result = await axios.get('/department/list'),
      data = result.data;
    // console.log(result)
    if (result.code !== 0) {
      alert("部门信息获取失败，请联系管理员！")
      return;
    }
    let str = ``;
    data.forEach(item => {
      let { id, name, desc } = item;
      str += `
        <tr>
          <td class="w10">${id}</td>
          <td class="w20">${name}</td>
          <td class="w40">${desc}</td>
          <td class="w20" departmentId="${id}">
            <a href="javascript:;">编辑</a>
            <a href="javascript:;">删除</a>
          </td>
        </tr>
      `;
    })
    $tbody.html(str);
  }
  function EditDeleHanlde() {
    $tbody.click(async ev => {
      let target = ev.target,
        $target = $(target),
        TAG = target.tagName,
        TEXT = target.innerText,
        departmentId = $target.parent().attr("departmentId");
      if (TAG === 'A') {
        if (TEXT === '编辑') {
          window.location.href = `departmentadd.html?departmentId=${departmentId}`;
          return;
        }
        if (TEXT === '删除') {
          let flag = confirm(`确定删除编号为${departmentId}的部门信息吗`);
          if (!flag) return;
          let result = await axios.get('/department/delete', { params: { departmentId } });
          if (result.code === 0) {
            bindHTML();
            return;
          }
          alert('删除失败，请重试！');
        }
      }
    })
  }
  return {
    init() {
      bindHTML();
      EditDeleHanlde();

    }
  }
})();
departmentModule.init();